/**
 * 📊 智能分析路由
 * 提供异常检测、健康评分、习惯分析等功能
 */

const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const AnomalyDetector = require('../services/detector');
const HealthScorer = require('../services/scorer');
const HabitAnalyzer = require('../services/habit-analyzer');

// 所有路由都需要认证
router.use(authenticateToken);

/**
 * 获取财务健康评分
 * GET /analysis/health-score?book_id=1&start_date=2025-01-01&end_date=2025-01-31
 */
router.get('/health-score', async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { book_id, start_date, end_date } = req.query;

    if (!book_id || !start_date || !end_date) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: book_id, start_date, end_date'
      });
    }

    // 计算健康评分
    const scoreData = await HealthScorer.calculateHealthScore(
      userId,
      parseInt(book_id),
      start_date,
      end_date
    );

    // 保存评分记录
    const scoreDate = new Date().toISOString().split('T')[0];
    await HealthScorer.saveScore(userId, parseInt(book_id), scoreDate, scoreData);

    res.json({
      code: 200,
      data: scoreData
    });

  } catch (error) {
    console.error('获取健康评分失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
});

/**
 * 获取历史健康评分
 * GET /analysis/health-score/history?book_id=1&limit=30
 */
router.get('/health-score/history', async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { book_id, limit = 30 } = req.query;

    if (!book_id) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: book_id'
      });
    }

    const db = require('../config/database');
    const [scores] = await db.query(`
      SELECT * FROM health_scores
      WHERE user_id = ? AND book_id = ?
      ORDER BY score_date DESC
      LIMIT ?
    `, [userId, parseInt(book_id), parseInt(limit)]);

    // 解析JSON字段
    const result = scores.map(s => ({
      ...s,
      suggestions: typeof s.suggestions === 'string' ? JSON.parse(s.suggestions) : s.suggestions
    }));

    res.json({
      code: 200,
      data: result
    });

  } catch (error) {
    console.error('获取历史评分失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
});

/**
 * 获取异常消费列表
 * GET /analysis/anomalies?book_id=1&status=pending&limit=20
 */
router.get('/anomalies', async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { book_id, status = 'pending', limit = 20 } = req.query;

    if (!book_id) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: book_id'
      });
    }

    const db = require('../config/database');
    let sql = `
      SELECT a.*, r.remark as description, r.amount, r.date, r.category
      FROM anomaly_records a
      JOIN records r ON a.record_id = r.record_id
      WHERE a.user_id = ? AND a.book_id = ?
    `;
    const params = [userId, parseInt(book_id)];

    if (status) {
      sql += ' AND a.status = ?';
      params.push(status);
    }

    sql += ' ORDER BY a.detected_at DESC LIMIT ?';
    params.push(parseInt(limit));

    const [anomalies] = await db.query(sql, params);

    res.json({
      code: 200,
      data: anomalies
    });

  } catch (error) {
    console.error('获取异常列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
});

/**
 * 处理异常（确认/忽略）
 * POST /analysis/anomalies/:id/action
 * Body: { action: 'confirmed' | 'ignored' }
 */
router.post('/anomalies/:id/action', async (req, res) => {
  try {
    const userId = req.user.user_id;
    const anomalyId = parseInt(req.params.id);
    const { action } = req.body;

    if (!action || !['confirmed', 'ignored'].includes(action)) {
      return res.status(400).json({
        code: 400,
        message: 'action 必须是 confirmed 或 ignored'
      });
    }

    await AnomalyDetector.updateAnomalyStatus(anomalyId, userId, action);

    res.json({
      code: 200,
      message: '操作成功'
    });

  } catch (error) {
    console.error('处理异常失败:', error);
    res.status(500).json({
      code: 500,
      message: '操作失败',
      error: error.message
    });
  }
});

/**
 * 手动触发异常检测（对指定记录）
 * POST /analysis/anomalies/detect
 * Body: { book_id: 1, record_id: 123 }
 */
router.post('/anomalies/detect', async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { book_id, record_id } = req.body;

    if (!book_id || !record_id) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: book_id, record_id'
      });
    }

    const anomalies = await AnomalyDetector.detectAllAnomalies(
      userId,
      parseInt(book_id),
      parseInt(record_id)
    );

    if (anomalies.length > 0) {
      await AnomalyDetector.saveAnomalies(userId, parseInt(book_id), anomalies);
    }

    res.json({
      code: 200,
      data: anomalies,
      message: `检测到 ${anomalies.length} 个异常`
    });

  } catch (error) {
    console.error('异常检测失败:', error);
    res.status(500).json({
      code: 500,
      message: '检测失败',
      error: error.message
    });
  }
});

/**
 * 获取消费习惯分析
 * GET /analysis/habits?book_id=1&start_date=2025-01-01&end_date=2025-01-31
 */
router.get('/habits', async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { book_id, start_date, end_date } = req.query;

    if (!book_id || !start_date || !end_date) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: book_id, start_date, end_date'
      });
    }

    const habitData = await HabitAnalyzer.analyzeHabits(
      userId,
      parseInt(book_id),
      start_date,
      end_date
    );

    res.json({
      code: 200,
      data: habitData
    });

  } catch (error) {
    console.error('获取习惯分析失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
});

/**
 * 获取消费趋势（含预测）
 * GET /analysis/trends?book_id=1&start_date=2025-01-01&end_date=2025-10-31
 */
router.get('/trends', async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { book_id, start_date, end_date } = req.query;

    if (!book_id || !start_date || !end_date) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: book_id, start_date, end_date'
      });
    }

    const trendData = await HabitAnalyzer.analyzeTrends(
      userId,
      parseInt(book_id),
      start_date,
      end_date
    );

    res.json({
      code: 200,
      data: trendData
    });

  } catch (error) {
    console.error('获取趋势分析失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
});

/**
 * 获取综合分析报告
 * GET /analysis/report?book_id=1&start_date=2025-01-01&end_date=2025-01-31
 */
router.get('/report', async (req, res) => {
  try {
    const userId = req.user.user_id;
    const { book_id, start_date, end_date } = req.query;

    if (!book_id || !start_date || !end_date) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: book_id, start_date, end_date'
      });
    }

    // 并行获取所有分析数据
    const [healthScore, habits, anomalies] = await Promise.all([
      HealthScorer.calculateHealthScore(userId, parseInt(book_id), start_date, end_date),
      HabitAnalyzer.analyzeHabits(userId, parseInt(book_id), start_date, end_date),
      AnomalyDetector.getPendingAnomalies(userId, parseInt(book_id), 10)
    ]);

    res.json({
      code: 200,
      data: {
        healthScore,
        habits,
        anomalies,
        period: { start_date, end_date }
      }
    });

  } catch (error) {
    console.error('获取分析报告失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
});

module.exports = router;

